package com.naruto.Interceptor.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.alibaba.fastjson.JSON;
import com.naruto.Interceptor.annotation.Auth;
import com.naruto.dao.AdminMapper;
import com.naruto.entity.AdminEntity;
import com.naruto.response.BaseResponse;

import tk.mybatis.mapper.entity.Example;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor extends HandlerInterceptorAdapter {
	@Autowired
	AdminMapper schoolMapper;
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		if (!handler.getClass().isAssignableFrom(HandlerMethod.class)) {
			System.out.println("cat cast handler to HandlerMethod.class");
			return false;
		}
		if (request.getRequestURI().contains("/springboot/swagger-resources") || request.getRequestURI().contains("api-docs") ) {
			return true;
		}
		// 公共的控制器可以通行 其他的 都必须进行token校验
		// 获取注解
		if (!request.getRequestURI().contains("publics") || request.getRequestURI().contains("login") ) {
			return true;
		}
		
		Auth auth = ((HandlerMethod) handler).getMethod().getAnnotation(Auth.class);
		if (auth == null) {
			System.out.println("cant find @Auth in this uri:" + request.getRequestURI());
			System.out.println("缺少权限");
			response.setStatus(200);
			response.setCharacterEncoding("gbk");
			PrintWriter pw = response.getWriter();
			BaseResponse adminLoginResp = new BaseResponse();
			adminLoginResp.setStatus("444");
			adminLoginResp.setResultMsg("缺少权限");
			String json = JSON.toJSONString(adminLoginResp);
			pw.print(json);
			return false;
		}
		// 从参数中取出用户身份并验证  约定过滤
		String admin = auth.user();
		if (!admin.equals(request.getParameter("user"))) {
			System.out.println("permission denied");
			response.setStatus(403);
			return false;
		}
		
		String token =request.getHeader("tokenId");
		if(token!=null) 
		{
			Example example =new Example(AdminEntity.class);
			example.createCriteria().andEqualTo("tokenId",token);
			AdminEntity entitys = schoolMapper.selectOneByExample(example);
			if(entitys != null) 
			{
				return true;
			}
		}
		
		return false;
	}
}
